# Author: Mr.Xu
# @Time : 2019/12/19 11:20
from . import models
from rest_framework import serializers
import time
from libs.iPay import get_pay_url, alipay_gateway

class ProductModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Product
        fields = ["id","name","vip_type","price","real_price","order"]


class PayModelSerializer(serializers.ModelSerializer):
    product_pk = serializers.IntegerField(required=True)
    class Meta:
        model = models.Order
        fields = ["subject","price","real_price","pay_type","product_pk","vip_type"]

    def validate(self, attrs):
        # 取出商品主键们
        product_pk = attrs.pop("product_pk")

        try:
            # 先拿到商品对象，在得到价格。
            product_obj = models.Product.objects.get(pk=product_pk)
        except:
            raise serializers.ValidationError({"product_pk", "错误的商品主键"})

        real_price = attrs.get('real_price')
        price = attrs.get('price')
        if real_price != product_obj.real_price or price!= product_obj.price:
            raise serializers.ValidationError({"total_amount", "商品价格被恶意篡改"})


        # 生成订单号
        order_no = self._get_order_no()
        # 订单名
        subject = attrs.get('subject')
        # 生成订单链接
        order_string = get_pay_url( # 使用自己封装的生成订单字符串的链接
            out_trade_no=order_no,
            total_amount=float(real_price),
            subject=subject,
        )
        pay_url = alipay_gateway + order_string
        # 将支付链接保存在serializer对象中
        self.pay_url = pay_url
        self.order_no = order_no

        # 添加额外的入口字段
        attrs["out_trade_no"] = order_no
        # 视图类给序列化类传参,取出request对象，放进去
        attrs['user'] = self.context.get('request').user

        # 将所有的商品对象存放在校验数据中，辅助订单详情表商品信息的入库
        attrs['product'] = product_obj

        return attrs

    def _get_order_no(self):
        no = '%s' % time.time()
        return no.replace('.', '', 1)